package hd.util.load;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import hd.util.file.FileDownload;
import hd.util.file.FileInfo;
import hd.util.file.OnFileDownload;


/**
 * 文件下载
 * <p/>
 * Created by haidy on 14/11/4.
 */
public class FileLoader {

    public static final int FILE_NOT_FIND = 1;
    public static final int DOWNLOAD_FILE_FAIL = 2;
    public static final String HTTP_CONNECT_DISPOSITION = "Content-Disposition";
    private static final int FILE_INFO = 3;
    public static OnFileLoaderListener listener;
    private static OnFileDownload fileDownload;

    public static void setOnFileLoaderListener(final String url, final String savePath, final String fileName, final OnFileLoaderListener listener) {
        FileLoader.listener = listener;
        new Thread() {
            @Override
            public void run() {
                FileInfo info = FileDownload.loadFileInfo(url);
                if (info != null) {
                    InputStream is = info.getInputStream();
                    Map<String, List<String>> headers = info.getHeader();
//                    System.out.println(headers);
                    //解析文件大小、名称
                    String name = null;
                    long size;
                    if (headers.containsKey(HTTP_CONNECT_DISPOSITION) && fileName == null) {
                        try {
                            name = new String(headers.get(HTTP_CONNECT_DISPOSITION).get(0).getBytes("iso-8859-1"), "utf-8")
                                    .replace("attachment; filename=", "")
                                    .replace("\"", "");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                    size = info.getFileSize();

                    name = getFileName(fileName, name, url);

                    Message startMSG = new Message();
                    startMSG.what = START;
                    startMSG.obj = size;

                    handler.sendMessage(startMSG);

                    long loadSize = 0;
                    byte[] bytes = new byte[1024];
                    int len;
                    try {
                        File file = new File(savePath);
                        file.mkdirs();
                        file = new File(file, name);
                        FileOutputStream os = new FileOutputStream(file);
                        while ((len = is.read(bytes)) != -1) {
                            os.write(bytes, 0, len);
                            loadSize += len;
                            Message msg = new Message();
                            msg.what = LOADING;
                            msg.obj = loadSize;
                            handler.sendMessage(msg);
                        }
                        is.close();
                        os.close();
                        Message msg = new Message();
                        msg.what = FINISH;
                        msg.arg1 = 1;
                        msg.arg2 = DOWNLOAD_FILE_FAIL;
                        handler.sendMessage(msg);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Message msg = new Message();
                        msg.what = FINISH;
                        msg.arg1 = 0;
                        msg.arg2 = DOWNLOAD_FILE_FAIL;
                        handler.sendMessage(msg);
                    }
                } else {
                    Message msg = new Message();
                    msg.what = FINISH;
                    msg.arg1 = 0;
                    msg.arg2 = FILE_NOT_FIND;
                    handler.sendMessage(msg);
                }
            }

            private String getFileName(String fileName, String name, String url) {
                if (fileName != null)
                    return fileName;
                if (name != null && !name.trim().isEmpty())
                    return name;
                return url.substring(url.lastIndexOf("/") + 1, url.length());
            }
        }.start();
    }

    public static void setOnFileDownload(final String url, final OnFileDownload download) {
        fileDownload = download;
        new Thread() {
            @Override
            public void run() {
                FileInfo info = FileDownload.loadFileInfo(url);
                Message fileInfo = new Message();
                download.setFileInfo(info);
                fileInfo.what = FILE_INFO;
                fileInfo.obj = info;
                handler.sendMessage(fileInfo);
            }
        }.start();
    }

    private static final int START = 0;//开始下载
    private static final int LOADING = 1;//正在下载
    private static final int FINISH = 2;//结束

    private static Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case START:
                    listener.onStart((Long) msg.obj);
                    break;
                case LOADING:
                    listener.onLoading((Long) msg.obj);
                    break;
                case FINISH:
                    listener.onFinish(msg.arg1 == 1, msg.arg2);
                    break;
                case FILE_INFO://文件信息
                    fileDownload.onLoadFileInfo((FileInfo) msg.obj);
                    break;
            }
        }
    };

    public interface OnFileLoaderListener {
        void onStart(long size);

        void onLoading(long length);

        void onFinish(boolean success, int statue);
    }
}